package com.gec.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gec.vo.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component("MyFailureHandler")
public class MyFailureHandler implements AuthenticationFailureHandler {

    private Result result;

    public Result getResult() {
        return result;
    }

    public void setResult(Result result) {
        this.result = result;
    }

    /**
     * @param request   请求对象
     * @param response  应答对象
     * @param exception
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("text/json;charset=utf-8");

        if (this.result == null) {
            Result localResult = new Result();
            localResult.setCode(1);
            localResult.setError(403);
            localResult.setMsg(exception.getMessage());

            result = localResult;
        }
        ServletOutputStream out = response.getOutputStream();

        //json对象
        ObjectMapper om = new ObjectMapper();
        om.writeValue(out, result);

        out.flush();
        out.close();
    }
}
